package niuke.jianZhiOffer;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.Scanner;
import java.util.Stack;

/**
 * 输入一个链表，从尾到头打印链表每个节点的值。
 * Created by Administrator on 2018/5/20.
 */
class  ListNode{
    int val;
    ListNode nextNode;

     ListNode listAddEnd(ListNode head,int nodeData)  	//追加结点
    {
        ListNode node,htemp;
        if((node = new ListNode())==null)
        {
            System.out.print("申请内存失败！\n");
            return null;  							//分配内存失败
        }
        else
        {
            node.val=nodeData; 				//保存数据
            node.nextNode=null;  				//设置结点指针为空，即为表尾
            if(head==null)  						//头指针
            {
                head=node;
                return head;
            }
            htemp=head;
            while(htemp.nextNode!=null) 			//查找链表的末尾
            {
                htemp=htemp.nextNode;
            }
            htemp.nextNode=node;
            return head;
        }
    }
}

public class PrintListFromTailToHead {
    static ArrayList<Integer> printListFromTailToHeadWay(ListNode listNode) {
        Stack<Integer> stack = new Stack<>();
        while (listNode != null) {
            stack.push(listNode.val);
            listNode = listNode.nextNode;
        }

        ArrayList<Integer> list = new ArrayList<>();
        while (!stack.isEmpty()) {
            list.add(stack.pop());
        }
        return list;
    }

    public static void main(String[] args){
        ListNode head = null;
        ListNode listNode = new ListNode();

        Scanner input = new Scanner(System.in);
		//获取输入的整数序列
		String str = input.nextLine();
		String[] strings = str.split(" ");
		//转为整数数组
		int[] arr = new int[strings.length];
		for (int i = 0; i < strings.length; i++) {
            arr[i] = Integer.parseInt(strings[i]);
            System.out.println("before:"+arr[i]);
            head=listNode.listAddEnd(head,arr[i]);
        }

        ArrayList<Integer> arrList = printListFromTailToHeadWay(head);
        Iterator it = arrList.iterator();
        while (it.hasNext()){
            System.out.println("after:"+it.next());
        }
    }

}
